package com.gtlab1207.br_awareness.ctrls;

import com.gtlab1207.br_awareness.common.*;
import com.gtlab1207.br_awareness.ctrls.BaseCtrl;
import com.gtlab1207.br_awareness.models.domain.User;
import com.gtlab1207.br_awareness.models.dto.UserPhoneDto;
import com.gtlab1207.br_awareness.services.LogRecordWriteTimerTask;
import com.gtlab1207.br_awareness.services.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;

/**
 * 通用业务控制层
 */
@RestController
@RequestMapping("/api/common")
public class CommonCtrl extends BaseCtrl {
    @Autowired
    UserService userService;

    /**
     * @param str 需加密的字符串
     * @return
     */
    @GetMapping("/encrypt")
    public String encrypt(String str){
        return AESUtil.Encrypt(str);
    }

    /**
     * 用户登陆
     * @param phone
     * @param password
     * @param code
     * @param request
     * @return
     */
    @PostMapping("/login")
    public Result login(@RequestParam(name = "phone",required = true) String phone,
                        @RequestParam(name = "password",required = true) String password,
                        @RequestParam(name = "code",required = true) String code,
                        HttpServletRequest request){
        String imgCode= (String) this.getValueFromSession("imgcode",request);
        String lowerCode=code.toLowerCase();
        Map<String,Object> result=new HashMap<>();
        System.out.println(request.getSession().getId()+" "+"front:"+lowerCode+" session:"+imgCode);
        //判断验证码是否正确
        if(imgCode!=null&&imgCode.equals(lowerCode)){
            this.removeValueFromSession("imgcode",request);

            //判断账号是否存在
            User user = (User)userService.getUserByPhone(phone).get("data");
            if(user!=null){
                if(password!=null){
                    password = password.trim();
                }
                //AES加密
                String password1 = AESUtil.Encrypt(password);
                //判断密码是否正确
                if(password1.equals(user.getPassword())){
                    user.setPassword(null);
                    this.setValueToSession(Constant.USER_SESSION,user,request);
                    result.put("phone",user.getPhone());
                    result.put("nickname",user.getNickname());
                    return send(Codes.SUCCESS,result);
                    //密码错误返回报错信息
                }else{
                    return send(Codes.PASS_ERROR);
                }
                //不存在返回手机号不存在
            }else {
                return send(Codes.NUM_NO_EXIST);
            }
        }
        //验证码错误
        return send(Codes.CODE_ERROR);
    }

    /**
     * 判断是否登录
     * @param request HttpServletRequest
     * @return 操作结果
     */
    @GetMapping("/login/status")
    public Result isLogin(HttpServletRequest request){
        if(this.getValueFromSession(Constant.USER_SESSION,request)!=null){
            User user = (User)this.getValueFromSession(Constant.USER_SESSION,request);
            return send(Codes.LOGINED,user);
        }else{
            return send(Codes.NO_LOGIN);
        }
    }

    /**
     * 用户登出
     * @param request
     * @return
     */
    @GetMapping("/logout")
    public Result adminLogout(HttpServletRequest request){
        if(this.getValueFromSession(Constant.USER_SESSION,request)!=null){
            this.removeValueFromSession(Constant.USER_SESSION,request);
            return send(Codes.SUCCESS);
        }else{
            return send(Codes.NO_LOGIN);
        }
    }

    /**
     *更改密码
     * @param beforePass
     * @param afterPass
     * @param request
     * @return
     */
    @PutMapping("/user/pass")
    public Result changePassword(@RequestParam(name = "beforePass",required = true) String beforePass,
                                 @RequestParam(name = "afterPass",required = true) String afterPass,
                                 HttpServletRequest request){
        User user = (User) this.getValueFromSession(Constant.USER_SESSION, request);
        String phone = user.getPhone();
        User temp = (User)userService.getUserByPhone(phone).get("data");
        if(beforePass!=null){
            beforePass=beforePass.trim();
        }
        //AES加密
        String beforePass1 = AESUtil.Encrypt(beforePass);
        if(afterPass!=null){
            afterPass=afterPass.trim();
        }
        //判断旧密码是否一致
        if (beforePass1.equals(temp.getPassword())) {
            User result = new User();
            result.setId(temp.getId());
            result.setPassword(afterPass);
            userService.updateUser(result);
            return send(Codes.SUCCESS);
        }
        return send(Codes.OLD_PASS_ERROR);
    }

    /**
     *更改手机号
     * @param userPhoneDto
     * @param request
     * @return
     */
    @PutMapping("/user/phone")
    public Result changePhone(@Valid UserPhoneDto userPhoneDto,
                              HttpServletRequest request){
        User user = (User) this.getValueFromSession(Constant.USER_SESSION, request);
        String phone = user.getPhone();
        User temp = (User)userService.getUserByPhone(phone).get("data");
        //AES加密
        String password = AESUtil.Encrypt(userPhoneDto.getPassword());
        //判断旧密码是否一致
        if (password.equals(temp.getPassword())) {
            //判断手机账号是否存在
            Map<String, Object> params = userService.getUserByPhone(userPhoneDto.getPhone());
            if(params.get("data")!=null){
                return this.send(3,"账号已存在");
            }
            User result = new User();
            result.setId(temp.getId());
            result.setPhone(userPhoneDto.getPhone());
            userService.updateUser(result);
            //更新session内容
            Map<String, Object> userById = userService.getUserById(temp.getId());
            User user1 = (User)userById.get("data");
            this.setValueToSession(Constant.USER_SESSION,user1,request);
            return send(Codes.SUCCESS);
        }
        return send(Codes.PASS_ERROR);
    }

    /**
     * 登录用户获取个人信息
     * @param request
     * @return
     */
    @GetMapping("/user/info")
    public Result userInfo(HttpServletRequest request){
        Map<String,Object> map = new HashMap<>();
        if(this.getValueFromSession(Constant.USER_SESSION,request)!=null){
            User user = (User)this.getValueFromSession(Constant.USER_SESSION, request);
            map.put("data",user);
        }
        return this.send(map);
    }

    /**
     * 获取图片验证码
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @GetMapping(value = "/imgCode")
    public String getCode(HttpServletRequest request, HttpServletResponse response) throws Exception{
        response.setContentType("image/jpeg");
        //禁止图像缓存
        response.setHeader("Pragma","no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        String imgcode = CaptchaUtil.outputCaptcha("4","120","40",null,null,null,null,request,response);
        this.setValueToSession("imgcode",imgcode,request);
        System.out.println( request.getSession().getId()+" "+imgcode);
        return null;
    }

}
